package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.ExerciseDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Exercise;
import com.itheima.service.ExerciseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service(interfaceClass = ExerciseService.class)
@Transactional
public class ExerciseServiceImpl implements ExerciseService {

    @Autowired
    private ExerciseDao exerciseDao;

    @Override
    public void add(List<Exercise> exerciseList) {
        //判断是否为空
        if(exerciseList!=null&&exerciseList.size()>0){
            for (Exercise exercise : exerciseList) {
                //查询此膳食名称是否存在
                Long count= exerciseDao.findCountByExerciseName(exercise.getName());
                if(count>0){
                    //存在则修改
                    exerciseDao.editByExerciseName(exercise);
                }else {
                    //不存在则添加
                    exerciseDao.add(exercise);
                }
            }
        }

    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        //使用PageHelper进行分页查询
        PageHelper.startPage(currentPage,pageSize);
        Page<Exercise> page = exerciseDao.selectByCondition(queryString);

        //将Page对象转换为PageResult对象
        PageResult result = new PageResult(page.getTotal(),page.getResult());

        return result;
    }

    @Override
    public List<Exercise> finAll() {
        return exerciseDao.findAll();
    }


    @Override
    public List<String> findExerciseByOrderDate(Date date) {
        int id = exerciseDao.findInterventionIdByOrderDate(date);
        return exerciseDao.findExerciseByInterventionId(id);
    }

    @Override
    public void addExercise(Exercise exercise) {
        exerciseDao.addExercise(exercise);
    }

    @Override
    public Exercise findById(Integer sid) {
        return exerciseDao.findById(sid);
    }

    @Override
    public void edit(Exercise exercise) {
        exerciseDao.edit(exercise);
    }

    @Override
    public void deleteById(Integer sid) {
        exerciseDao.deleteById(sid);
    }
}
